<template>
	<div class="bg-gray-500/5 p-1 gap-1 flex flex-col h-full">

		<!--用例功能-->
		<section class="flex h-1/7 gap-1 flex-col">
			<header v-if="isNullTestcase(currentTestcase)" class="flex gap-x-2 items-center">
				<n-tag type="warning" size="large" class="bg-zinc-800 text-lg font-bold">当前未打开任何用例!</n-tag>
				<n-tag size="large" class="bg-zinc-800 text-lg font-bold">右侧选中用例单击打开!</n-tag>
			</header>
			<header class="flex gap-x-2 items-center" v-else>
				<n-tag size="large" class="bg-zinc-800 text-lg font-bold">
					{{ '用例名称:' }} {{ currentTestcase?.label }}
				</n-tag>
				<n-tag size="large" class="bg-zinc-800 text-lg font-bold">
					{{ '作者:' }} {{ currentTestcase?.author }}
				</n-tag>
				<n-tag size="large" class="bg-zinc-800 text-lg font-bold">
					{{ '创建日期:' }} {{ currentTestcase?.createTime }}
				</n-tag>
				<n-tag size="large" class="bg-zinc-800 text-lg font-bold">
					{{ '最后修改:' }} {{ currentTestcase?.modifyTime }}
				</n-tag>
			</header>

			<!--功能区域-->
			<n-space align="center" class="w-1/2" :wrap="false" :size="5">
				<!--用例相关功能-->
				<div class="p-1 h-16 rounded bg-gray-500/25 flex flex-col w-fit">
					<div>
						<n-text class="text-base">用例</n-text>
						<n-text tag="q" depth="3">通过Ctrl+S快速保存</n-text>
					</div>

					<n-space size="small">
						<n-dropdown
							trigger="click"
							:options="testcaseOption"
							@select="handleSelect"
							placement="left-start"
						>
							<n-button type="default" secondary size="small">
								用例管理
								<!-- 用于导入的隐藏 upload -->
								<n-upload
									ref="uploadRef"
									class="hide"
									:show-file-list="false"
									@change="importTestcase"
								/>
							</n-button>
						</n-dropdown>

						<n-button type="success" secondary size="small" @click="saveTestcase">保存</n-button>
						<n-button type="error" secondary size="small" @click="closeTestcase">清空并关闭当前用例
						</n-button>
					</n-space>
				</div>

				<!--功能区域搜索指令-->
				<div class="p-1 h-16  rounded bg-gray-500/25">
					<n-text class="text-base">快捷搜索</n-text>
					<n-text class="ms-2" tag="q" depth="3">在当前用例中搜索(通过备注)</n-text>
					<n-select class="w-auto" v-model:value="filterValue"
							  filterable
							  :filter="intoViewByFilter"
							  placeholder="选择/搜索指令(通过备注)"
							  :options="currentTestcase.commandList"
							  label-field="remark" value-field="remark"></n-select>
				</div>

			</n-space>
		</section>

		<n-flex class="h-6/7" :wrap="false">
			<!--指令列表组件-->
			<CommandList class="w-1/2 h-full px-1.5"
						 @update:commandList="handleUpdateCmdList"
						 :command-list="currentTestcase?.commandList"
						 :device-list="deviceList"></CommandList>

			<!--筛选遥测界面-->
			<section class="w-1/2 h-full bg-zinc-800 rounded mb-7 flex flex-col px-1.5">
				<Telemetry :excludes-columns="['序号', '源码值', '操作']"
						   :is-filter="true"
						   :labels="siftField"/>
			</section>
		</n-flex>

	</div>
</template>

<script setup lang="ts">
import {ref, onMounted, computed, onUnmounted, h, watch} from 'vue'
import {ArrowImport20Filled, ArrowExportLtr20Filled, CloudLink20Filled} from '@vicons/fluent'
import {useMessage, NIcon} from 'naive-ui'
import {storeToRefs} from "pinia";
import {useUserProfile} from "@/stores/useUserProfile.js"
import {fuzzyMatch} from "@/utils/fuzzy.js"
import CommandList from "@/views/Control/components/CommandList.vue";
import Telemetry from "@/views/Telemetry/Index.vue";


const message = useMessage()
const userProfile = useUserProfile()
const {setUserProfile, addTestcase, removeTestcase} = userProfile
// 获取配置
const {profile, deviceList} = storeToRefs(userProfile)

const isEmpty = v =>
	(Array.isArray(v) && !v.length) ||
	(typeof v === 'object' && v !== null && !Object.keys(v).length)

// 判断该用例中是否有指令
const isEmptyCmdList = v => isEmpty(v?.commandList)
// 判断该用例是否存在
const isNullTestcase = v => !v?.key

function renderIcon(icon: Component) {
	return () => {
		return h(NIcon, null, {
			default: () => h(icon)
		})
	}
}

// 用例功能渲染
const testcaseOption = [
	{
		label: '导入',
		key: 'import',
		icon: renderIcon(ArrowImport20Filled)
	},
	{
		label: '导出',
		key: 'export',
		icon: renderIcon(ArrowExportLtr20Filled)
	},
	{
		label: '加载共享用例',
		key: 'load',
		icon: renderIcon(CloudLink20Filled)
	}
]
const uploadRef = ref(null)
const handleSelect = (key: string | number) => {
	// 导入用例
	if (key === 'import') {
		uploadRef.value?.openOpenFileDialog()
	} else if (key === 'export') {
		// 导出用例
		exportTestcase()
	} else if (key == "load") {
		// 从共享空间中加载用例
		loadTestcase()
	}
}
// const currentTestcase = {commandList: []}
// 可感知pinia更改
const currentTestcase = computed({
	get: () => {
		if (isEmpty(profile.value.currentTestcase)) {
			return {commandList: []}
		} else {
			return profile.value.currentTestcase
		}
	},
	set: (newValue) => {
		// 更新配置文件中的值
		profile.value.currentTestcase = newValue;
	}
});

const filterValue = ref(null)
const intoViewByFilter = (patter, option) => {
	const result = fuzzyMatch(currentTestcase.value.commandList, "remark", patter);
	// 使用 some 方法检查是否有任何 remark 与 option.remark 匹配
	return result.some(item => item.remark === option.remark);
	// todo: 触发select后把视图移向指定指令,并且高亮
}
const handleUpdateCmdList = (cmdList) => {
	// 更新 computed 中的值，它会通过 setter 更新到 profile 中
	currentTestcase.value.commandList = cmdList;
};
/**
 * 保存当前打开的用例
 */
const saveTestcase = () => {
	console.log(currentTestcase.value.commandList)
	// 保存用例(保存指令)
	// 删除旧的再存入新的
	const lastIndex = profile.value.testcases[0].children.findIndex(item => item.id === currentTestcase.value.id)
	// 删除旧的用例
	removeTestcase(lastIndex)
	// 加入新的用例
	addTestcase(currentTestcase.value)
	message.success(`用例 ${currentTestcase.value.label} 保存成功!`)
}

const closeTestcase = () => {
	// 当前打开用例对象置空并清除掉缓存
	currentTestcase.value.commandList = []
	console.log(currentTestcase.value.commandList)
	setUserProfile("currentTestcase", {commandList: []})
	message.success("用例已关闭!")
}
const exportTestcase = () => {
	function downloadObjectAsJson(exportObj, exportName) {
		const dataStr = 'data:text/json;charset=utf-8,' + encodeURIComponent(JSON.stringify(exportObj));
		const downloadAnchorNode = document.createElement('a');
		downloadAnchorNode.setAttribute('href', dataStr);
		downloadAnchorNode.setAttribute('download', exportName + '.json');
		document.body.appendChild(downloadAnchorNode);
		downloadAnchorNode.click();
		downloadAnchorNode.remove();
	}

	// 调用函数触发下载
	downloadObjectAsJson(currentTestcase.value, currentTestcase.value.label);
}
const importTestcase = ({file}) => {
	// 处理
	if (file) {
		const reader = new FileReader();

		reader.onload = function (e) {
			try {
				const jsonData = JSON.parse(e.target.result);
				currentTestcase.value = jsonData
				saveTestcase()
			} catch (error) {
				console.error('反序列化 JSON 时出错:', error);
			}
		};

		reader.onerror = function () {
			console.error('读取文件时出错');
		};

		reader.readAsText(file.file);

	}
}

const loadTestcase = () => {

}

const siftField = computed(() => {
	if (isEmpty(currentTestcase)) return []
	// 当值发生变动时, 找到当前选中的指令行的遥测关系字段
	const obj = currentTestcase.value?.commandList?.filter(item => item.selected)[0]
	if (obj?.selected) {
		return obj.relationshipField
	}
	return []
})
const handleSaveShortcut = (event) => {
	if (event.ctrlKey && event.key.toLowerCase() === "s") {
		event.preventDefault(); // 阻止浏览器默认的“保存网页”行为
		console.log("Ctrl+S 被触发！");
		saveTestcase()
	}
};

onMounted(() => {
	window.addEventListener("keydown", handleSaveShortcut);
	// setUserProfile("currentTestcase", profile.value.testcases[0].children.at(-1))
});

onUnmounted(() => {
	window.removeEventListener("keydown", handleSaveShortcut);

});
</script>
<style scoped>

</style>